package com.yunji.generate.fxml;

import javafx.geometry.Pos;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.TableCell;

/**
 * @author hushuang
 * @since 2019/9/22
 */
public class BooleanCell<T> extends TableCell<T, Boolean> {

    private CheckBox checkBox;

    public BooleanCell() {
        this(true);
    }

    public BooleanCell(boolean editable) {
        checkBox = new CheckBox();
        checkBox.setDisable(!editable);
        checkBox.selectedProperty().addListener((observable, oldValue, newValue) -> {
            if (isEditing()) {
                commitEdit(newValue == null ? false : newValue);
            }
        });
        this.setAlignment(Pos.CENTER);
        this.setGraphic(checkBox);
        this.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
        this.setEditable(editable);
    }

    @Override
    public void updateItem(Boolean item, boolean empty) {
        super.updateItem(item, empty);
        if (!isEmpty()) {
            checkBox.setSelected(item);
        }
        this.setGraphic(isEmpty() ? null : checkBox);
    }
}